<template>
  <div class="edit-company">
    <div class="mycard">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
        <div class="tip-title">公司信息</div>
        <div class="box">
          <el-form-item label="公司名称：" prop="name">
            <el-autocomplete
              :value="ruleForm.name"
              value-key="name"
              size="small"
              ref="companyRef"
              :fetch-suggestions="querySearchAsync"
              @select="selectAutocomplete"
              @input="inputAutocomplete"
            >
            </el-autocomplete>
          </el-form-item>

          <el-form-item label="所在地区：" prop="Area">
            <el-select
              v-model="ruleForm.Area"
              placeholder="请选择"
              @change="currencyChange(ruleForm.Area)"
            >
              <el-option
                v-for="item in AreaOption"
                :key="item.id"
                :value="item.id"
                :label="item.dname"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="公司类型：" prop="companyType">
            <el-radio-group v-model="ruleForm.companyType" @change="change">
              <el-radio
                :label="item.id"
                v-for="item in companyOption"
                :key="item.id"
                >{{ item.dname }}</el-radio
              >
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="发票类型："
            prop="invioceType"
            v-if="ruleForm.Area == 'FArea01'"
            class="fplx"
          >
            <el-input v-model="invioceType" disabled></el-input>
          </el-form-item>
          <el-form-item label="" prop="" v-else> </el-form-item>
          <!-- <el-form-item label="企业性质" prop="Natrue">
              <el-select
                v-model="ruleForm.Natrue"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in natrueOption"
                  :key="item.id"
                  :value="item.id"
                  :label="item.dname"
                ></el-option>
              </el-select>
            </el-form-item> -->

          <!-- <el-row :gutter="gutter">
          <el-col :span="span">
            <el-form-item label="发票类型" prop="invioceType">
              <el-select
                v-model="ruleForm.invioceType"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in invioceOption"
                  :key="item.id"
                  :value="item.id"
                  :label="item.dname"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->

          <el-form-item label="上传资料：" prop="pictrueIds">
            <div class="upload-container">
              <div
                class="boxPic"
                @mouseover="handleMouseover()"
                @mouseleave="handleMouseleave()"
              >
                <div class="avatarL" v-if="isShow1">
                  <i
                    class="el-icon-zoom-in"
                    @click="handlePictureCardPreview(1)"
                  ></i>

                  <i class="el-icon-delete" @click="handleRemove(1)"></i>
                </div>
                <img
                  v-if="fileObj.name && fileObj.imgType == 1"
                  :src="
                    fileObj.name.indexOf('.pdf') == -1
                      ? fileObj.urls
                      : imagePdfUrl
                  "
                  class="avatar"
                />
                <CustomUpload
                  v-else
                  :imgType="1"
                  :tips="firstTips"
                  :imageUrl="imageUrl1"
                  @childEvent="handleEvent"
                  @imageUrl="setimageUrl"
                ></CustomUpload>
              </div>

              <!-- <CustomUpload
                  :imgType="2"
                  tips="身份证正面"
                  @childEvent="handleEvent"
                ></CustomUpload>
                <CustomUpload
                  :imgType="3"
                  tips="身份证反面"
                  @childEvent="handleEvent"
                ></CustomUpload> -->
              <div
                class="boxPic"
                @mouseover="handleMouseover4()"
                @mouseleave="handleMouseleave4()"
              >
                <div class="avatarL" v-if="isShow4">
                  <i
                    class="el-icon-zoom-in"
                    @click="handlePictureCardPreview(4)"
                  ></i>
                  <i class="el-icon-delete" @click="handleRemove(4)"></i>
                </div>
                <img
                  v-if="fileObj4.name && fileObj4.imgType == 4"
                  :src="
                    fileObj4.name.indexOf('.pdf') == -1
                      ? fileObj4.urls
                      : imagePdfUrl
                  "
                  class="avatar"
                />
                <CustomUpload
                  v-else
                  :imgType="4"
                  :tips="otherTips"
                  :imageUrl="imageUrl4"
                  @childEvent="handleEvent"
                  @imageUrl="setimageUrl"
                ></CustomUpload>
              </div>
            </div>
            <span class="tip-msg"
              >仅支持jpg、png、gif、pdf格式上传，大小不超过5M</span
            >
          </el-form-item>
        </div>
        <div class="tip-title">账户信息</div>
        <div class="box">
          <el-form-item label="币种：" prop="currency">
            <el-input v-model="ruleForm.currency" disabled></el-input>
          </el-form-item>

          <el-form-item label="收款公司：" prop="CollectionCompany">
            <el-input v-model="ruleForm.CollectionCompany"></el-input>
          </el-form-item>

          <el-form-item label="开户银行：" prop="openBank">
            <el-input v-model="ruleForm.openBank"></el-input>
          </el-form-item>

          <el-form-item label="账号：" prop="accountNum">
            <el-input v-model="ruleForm.accountNum"></el-input>
          </el-form-item>

          <el-form-item
            label="银行地址："
            prop="bankAddress"
            v-show="ruleForm.Area == 'FArea03'"
          >
            <el-input v-model="ruleForm.bankAddress"></el-input>
          </el-form-item>

          <el-form-item
            label="swift code"
            prop="swiftCode"
            v-show="ruleForm.Area == 'FArea03'"
          >
            <el-input v-model="ruleForm.swiftCode"></el-input>
          </el-form-item>

          <el-form-item
            label="中转银行："
            prop="transitBank"
            v-show="ruleForm.Area == 'FArea03'"
          >
            <el-input v-model="ruleForm.transitBank"></el-input>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <el-dialog :visible.sync="dialogVisible" class="eldialogVisible" :title="fileObj.name">
      <img
        width="100%"
        :src="dialogImageUrl"
        alt=""
        v-if="dialogImageUrl.indexOf('.pdf') == -1"
      />
      <iframe
        :src="dialogImageUrl"
        height="500px;"
        width="100%"
        v-else
      ></iframe>
    </el-dialog>
    <div class="mydiv">
      <el-button
        type="primary"
        @click="handleAddCompany('ruleForm')"
        :disabled="hasBaseInfo2"
        >确认</el-button
      >
      <el-button @click="handleRever" class="resletBtn">取消</el-button>
    </div>
  </div>
</template>

<script>
import {
  addCompany,
  searchCompanyTYC,
  checkCompany,
  searchDistrict,
  searchCompany,
  companyDetail,
} from "@/api/myCompany.js";
import FileUploader from "@/components/FileUploader";
import CustomUpload from "@/components/CustomUpload";
import {
  checkCollectionCompany,
  checkopenBank,
  checkaccountNum,
} from "@/utils/validate.js";
export default {
  name: "add",
  data() {
    return {
      fileObj: {
        name: "",
        urls: "",
        imgType: "1",
      },
      fileObj4: {
        name: "",
        urls: "",
        imgType: "4",
      },
      isShow1: false,
      isShow4: false,
      dialogVisible: false,
      dialogImageUrl: "",
      imagePdfUrl: require("../../../assets/images/pdf.png"),
      firstTips: "营业执照",
      otherTips: "其他证明文件",
      invioceType: "增值税专用发票",
      ruleForm: {
        name: "", // 公司名称
        Area: "", // 国别地区
        companyType: "", // 公司类型
        Natrue: "",
        invioceType: "",
        //  工商信息
        // Uscc: "",
        // Corperation: "",
        // RegistDate: "",
        // RegistCurrency: "",
        // RegistFund: "",
        // Employees: "",
        // BusinessState: "",
        // BusinessScope: "",
        // countryId: "",
        // AboradCurrency: "",
        // companyRegisteredAddress: "",
        // 收款信息
        currency: "人民币",
        CollectionCompany: "",
        openBank: "",
        accountNum: "",
        bankAddress: "",
        swiftCode: "",
        transitBank: "",
        //上传文件
        pictrueIds: [],
      },
      AreaOption: [],
      companyOption: [],
      natrueOption: [],
      invioceOption: [],
      currencyOption: [],
      originOption: [],
      AboradCurrencyOption: [],
      rules: {
        name: [
          { required: true, message: "请填写公司信息", trigger: "change" },
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value && value.length < 3) {
                return callback(new Error("最少为三个字符"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        Area: [
          { required: true, message: "请选择国别地区", trigger: "change" },
        ],
        companyType: [
          { required: true, message: "请选择公司类型", trigger: "change" },
        ],
        Natrue: [
          { required: true, message: "请选择企业性质", trigger: "change" },
        ],
        pictrueIds: [
          { required: true, message: "请选择图片", trigger: "change" },
        ],
        currency: [
          { required: true, message: "请选择币种", trigger: "change" },
        ],
        CollectionCompany: [
          {
            required: true,
            message: "请输入收款公司",
            validator: checkCollectionCompany,
            trigger: "blur",
          },
        ],
        openBank: [
          {
            required: true,
            message: "请输入开户银行",
            validator: checkopenBank,
            trigger: "blur",
          },
        ],
        accountNum: [
          {
            required: true,
            message: "请输入账号",
            validator: checkaccountNum,
            trigger: "blur",
          },
        ],
      },
      hasBaseInfo: false,
      hasBaseInfo2: false,
      imageUrl1: "",
      imageUrl4: "",
    };
  },
  components: {
    FileUploader,
    CustomUpload,
  },
  created() {},
  mounted() {
    this.handleSelectChange();
    if (this.$route.query.type && this.$route.query.type == 300) {
      this.companyDetail_();
    }
    // 切换页面保留之前的数据
    if (sessionStorage.getItem("ruleForm")) {
      let cloneRuleForm = JSON.parse(sessionStorage.getItem("ruleForm"));
      this.ruleForm = JSON.parse(JSON.stringify(cloneRuleForm));
    }
  },
  methods: {
    handleMouseleave() {
      this.isShow1 = false;
    },
    handleMouseover() {
      this.isShow1 = true;
    },
    handleMouseleave4() {
      this.isShow4 = false;
    },
    handleMouseover4() {
      this.isShow4 = true;
    },
    handlePictureCardPreview(type) {
      this.dialogVisible = true;
      this.dialogImageUrl = type == 1 ? this.fileObj.urls : this.fileObj4.urls;
    },
    handleRemove(type) {
      if (type == 1) {
        this.isShow1 = false;
        this.imageUrl1 = "";
        this.fileObj = {
          name: "",
          urls: "",
          imgType: "1",
        };
      } else {
        this.isShow4 = false;
        this.imageUrl4 = "";
        this.fileObj4 = {
          name: "",
          urls: "",
          imgType: "4",
        };
      }
      let arr = [];
      this.ruleForm.pictrueIds.length && this.ruleForm.pictrueIds.forEach((item)=>{
        if (type != item.customType) {
          arr.push(item);
        }
      })
      this.$set(this.ruleForm, "pictrueIds", arr);
    },
    setimageUrl(val, num) {
      if (num == 1) {
        this.imageUrl1 = val;
      }
      if (num == 4) {
        this.imageUrl4 = val;
      }
    },
    companyDetail_() {
      let relationEnterpriseId = this.$route.query.relationEnterpriseId || "";
      if (relationEnterpriseId) {
        companyDetail({ relationEnterpriseId }).then((res) => {
          if (res.code == 200) {
            let result = res.result;

            // 基本信息
            this.$set(this.ruleForm, "name", result.name); // 公司名称
            this.$set(this.ruleForm, "Area", result.countryRegion); // 国别地区
            this.$set(this.ruleForm, "companyType", result.companyType); // 公司类型
            this.invioceType = result.invoicTypeName; // 发票类型
            let arr = [];
            result.files &&
              result.files.length &&
              result.files.forEach((item) => {
                arr.push({
                  id: item.id,
                  customType: item.customType,
                });
                if (item.customType == 1) {
                  this.imageUrl1 = item.fullPath;
                }
                if (item.customType == 4) {
                  this.imageUrl4 = item.fullPath;
                }
              });
            this.$set(this.ruleForm, "pictrueIds", arr); // 上传附件

            // 账户信息
            this.$set(this.ruleForm, "currency", result.currencyName); // 币种
            this.$set(
              this.ruleForm,
              "CollectionCompany",
              result.receivingCompany
            ); // 收款公司
            this.$set(this.ruleForm, "openBank", result.bankOfDeposit); // 开户银行
            this.$set(this.ruleForm, "accountNum", result.accountNumber); // 账号
            this.$set(this.ruleForm, "bankAddress", result.bankAddress); // 银行地址
            this.$set(this.ruleForm, "swiftCode", result.swiftCode); // swift code
            this.$set(this.ruleForm, "transitBank", result.transitBank); // 中转银行
          }
        });
      }
    },

    change() {
      this.otherTips =
        this.ruleForm.companyType === "Arg0697"
          ? "代理证明文件"
          : "其他证明文件";
    },
    currencyChange(val) {
      this.hasBaseInfo2 = false;
      this.hasBaseInfo = false;
      this.ruleForm.currency = "美元";
      this.invioceType = "";
      this.firstTips = "商业登记证";
      if (val == "FArea01") {
        this.ruleForm.currency = "人民币";
        this.invioceType = "增值税专用发票";
        this.firstTips = "营业执照";
        // (this.ruleForm.Uscc = ""),
        //   (this.ruleForm.Corperation = ""),
        //   (this.ruleForm.RegistDate = ""),
        //   (this.ruleForm.RegistCurrency = ""),
        //   (this.ruleForm.RegistFund = ""),
        //   (this.ruleForm.Employees = ""),
        //   (this.ruleForm.BusinessState = ""),
        //   (this.ruleForm.companyRegisteredAddress = ""),
        //   (this.ruleForm.BusinessScope = "");
        // this.GetBaseInfo();
      }
    },
    // 输入框内容发生变化后触发
    inputAutocomplete(val) {
      this.$set(this.ruleForm, "name", val);
      // this.GetBaseInfo();
      this.validateCompany();
    },
    // 选中下拉项的时候
    selectAutocomplete(val) {
      if (val) {
        this.$set(this.ruleForm, "name", val.name);
      }
    },
    querySearchAsync(query, cb) {
      if (query.length >= 3) {
        searchCompany({ Name: query.trim(), pageNum: 1, pageSize: 10 }).then(
          (res) => {
            if (res.success) {
              clearTimeout(this.timeout);
              this.timeout = setTimeout(() => {
                cb(res.result);
              }, 200);
            } else {
              cb([]);
            }
          }
        );
      } else {
        cb([]);
      }
    },
    handleEvent(id, customType, fileObj) {
      if (this.ruleForm.pictrueIds.length == 0) {
        this.ruleForm.pictrueIds.push({ id, customType });
      } else {
        const index = this.ruleForm.pictrueIds.findIndex(
          (item) => item.customType == customType
        );
        if (index != -1) {
          this.ruleForm.pictrueIds[index] = { id, customType };
        } else {
          this.ruleForm.pictrueIds.push({ id, customType });
        }
      }
      if (customType == 1) {
        this.fileObj = fileObj;
      } else {
        this.fileObj4 = fileObj;
      }
    },
    //查国别地区
    handleSelectChange() {
      searchDistrict().then((res) => {
        //国别地区
        this.AreaOption = res.result.country_and_region;
        this.$set(this.ruleForm, "Area", "FArea01");
        //公司类型
        this.companyOption = res.result.supplier_type;
        //企业性质
        this.natrueOption = res.result.enterprise_nature;
        //发票类型
        this.invioceOption = res.result.invoice_type;
        //币种
        this.currencyOption = res.result.currency;
        //国家地区
        this.originOption = res.result.country_of_origin;
        this.AboradCurrencyOption = res.result.currency;
      });
    },
    //校验公司是否已注册
    validateCompany() {
      if (this.ruleForm.name && this.ruleForm.name.length > 0) {
        checkCompany({ name: this.ruleForm.name }).then((res) => {
          if (res.success == false) {
            this.$message.error(res.message);
            this.hasBaseInfo2 = true;
          }
        });
      }
    },
    //添加公司
    handleAddCompany(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          let name = this.ruleForm.name; // 公司名称
          let companyTypeId = this.ruleForm.companyType; // 公司类型
          let countryRegionId = this.ruleForm.Area; // 国别地区
          let invoicTypeId = this.invioceOption.find(
            (item) => item.dname == this.invioceType
          )
            ? this.invioceOption.find((item) => item.dname == this.invioceType)
                .id
            : ""; // 发票类型

          let accountNumber = this.ruleForm.accountNum; // 账号
          let bankAddress = this.ruleForm.bankAddress; // 银行地址
          let bankOfDeposit = this.ruleForm.openBank; // 开户银行
          let currencyId = this.currencyOption.find(
            (item) => item.dname == this.ruleForm.currency
          ).id; // 币种

          let receivingCompany = this.ruleForm.CollectionCompany; // 收款公司
          let swiftCode = this.ruleForm.swiftCode; // swift code
          let transitBank = this.ruleForm.transitBank; // 中转银行
          let uploadFileVo = this.ruleForm.pictrueIds; // 上传附件

          let params = {
            accountNumber,
            bankAddress,
            bankOfDeposit,
            companyTypeId,
            countryRegionId,
            currencyId,
            invoicTypeId,
            name,
            receivingCompany,
            swiftCode,
            transitBank,
            uploadFileVo,
            // enterpriseNatureId: this.ruleForm.Natrue,
            // uscc: this.ruleForm.Uscc,
            // legalRepresentative: this.ruleForm.Corperation,
            // incorporation: this.ruleForm.RegistDate,
            // registerCurrency: this.ruleForm.RegistCurrency,
            // registeredCapital: this.ruleForm.RegistFund,
            // numberOfEmployees: this.ruleForm.Employees,
            // businessStatus: this.ruleForm.BusinessState,
            // companyRegisteredAddress: this.ruleForm.companyRegisteredAddress,
            // natureOfBusiness: this.ruleForm.BusinessScope,
            // pictureIds: this.ruleForm.pictrueIds,
            // countryId: this.ruleForm.countryId,
            // abroadRegisterCurrency: this.ruleForm.AboradCurrency,
          };

          // 判断是否是审核拒绝进来的
          let relationEnterpriseId =
            this.$route.query.relationEnterpriseId || "";
          if (relationEnterpriseId) {
            params.update = true;
          } else {
            params.update = false;
          }
          addCompany(params).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功!");
              this.ruleForm = {
                name: "",
                Area: "",
                companyType: "",
                Natrue: "",
                invioceType: "",

                currency: "人民币",
                CollectionCompany: "",
                openBank: "",
                accountNum: "",
                bankAddress: "",
                swiftCode: "",
                transitBank: "",
                //上传文件
                pictrueIds: [],
              };
              // this.ruleForm = {};
              // this.$refs.ruleForm.clearValidate()
              this.$router.push("/myCompany");
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    //查工商信息
    GetBaseInfo() {
      if (this.ruleForm.name && this.ruleForm.name.length > 3) {
        searchCompanyTYC({ companyName: this.ruleForm.name }).then((res) => {
          if (res.success) {
            let result = res.result;
            if (result) {
              this.ruleForm.Uscc = result.uscc;
              this.ruleForm.Corperation = result.legalRepresentative;
              this.ruleForm.RegistDate = result.incorporation;
              this.ruleForm.RegistCurrency = result.registerCurrency;
              this.ruleForm.RegistFund = result.registeredCapital;
              this.ruleForm.Employees = result.numberOfEmployees;
              this.ruleForm.BusinessState = result.businessStatus;
              this.ruleForm.companyRegisteredAddress =
                result.companyRegisteredAddress;
              this.ruleForm.BusinessScope = result.natureOfBusiness;
            }
          } else {
            (this.ruleForm.Uscc = ""),
              (this.ruleForm.Corperation = ""),
              (this.ruleForm.RegistDate = ""),
              (this.ruleForm.RegistCurrency = ""),
              (this.ruleForm.RegistFund = ""),
              (this.ruleForm.Employees = ""),
              (this.ruleForm.BusinessState = ""),
              (this.ruleForm.companyRegisteredAddress = ""),
              (this.ruleForm.BusinessScope = "");
          }
          if (this.ruleForm.Uscc == "" && this.ruleForm.Area == "FArea01") {
            this.hasBaseInfo2 = true;
          }
          if (this.ruleForm.Uscc && this.ruleForm.Area == "FArea01") {
            this.hasBaseInfo2 = false;
            this.hasBaseInfo = true;
          }
        });
      } else {
        this.hasBaseInfo2 = false;
        this.hasBaseInfo = false;

        (this.ruleForm.Uscc = ""),
          (this.ruleForm.Corperation = ""),
          (this.ruleForm.RegistDate = ""),
          (this.ruleForm.RegistCurrency = ""),
          (this.ruleForm.RegistFund = ""),
          (this.ruleForm.Employees = ""),
          (this.ruleForm.BusinessState = ""),
          (this.ruleForm.companyRegisteredAddress = ""),
          (this.ruleForm.BusinessScope = "");
      }
    },
    //返回
    handleRever() {
      this.$router.push("/myCompany");
    },
  },
  beforeDestroy() {
    // this.$store.commit("companyDetail", this.ruleForm);
    // 切换页面保留之前的数据
    window.sessionStorage.setItem("ruleForm", JSON.stringify(this.ruleForm));
  },
};
</script>

<style scoped lang="scss">
@import "../../../assets/styles/myCompany.scss";
</style>